/*
 * @Author: diana
 * @Date: 2023-05-05 21:52:34
 * @LastEditTime: 2023-05-06 19:50:35
 */
import React, { useEffect, useState } from "react";
import { ethers } from "ethers";

import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import Router from "next/router"

import abi from "../../../backend/artifacts/contracts/AddressInfo.sol/AddressInfo.json";
import { Box, Button, ButtonGroup, Divider, Heading, Input, Stack,Text, Textarea } from "@chakra-ui/react";
import {
  Accordion,
  AccordionItem,
  AccordionButton,
  AccordionPanel,
  AccordionIcon,
} from '@chakra-ui/react'
declare let window: any;
function App() {
  // 合约地址abi
  const contractAddress = "0x8A791620dd6260079BF849Dc5567aDC3F2FdC318";
  //合约编译的json文件
  const contractABI = abi.abi;
  const toatTime = 2
  // 接收参数
  const [currentAccount, setCurrentAccount] = useState("");
  const [name, setName] = useState("");
  const [message, setMessage] = useState("");

  const [allCoffee, setAllCoffee] = useState([]);

  // 检查是否连接钱包
  const checkIfWalletIsConnected = async () => {
    try {
      //window.ethereum
      const { ethereum } = window;
      // 获取当前网页连接的账户
      const accounts = await ethereum.request({ method: "eth_accounts" });

      if (accounts.length !== 0) {
        const currentAc = accounts[0];
        setCurrentAccount(currentAc);

        toast.success("Wallet is Connected", {
          position: "top-right",
          autoClose: toatTime,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
      } else {
        toast.warn("Make sure you have MetaMask Connected", {
          position: "top-right",
          autoClose: toatTime,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
      }
    } catch (e) {
      toast.error(`${e.message}`, {
        position: "top-right",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    }
  };

  // 连接钱包
  const connectWallet = async () => {
    try {
      const { ethereum } = window;
      if (!ethereum) {
        toast.warn("Make sure you have MetaMask Connected", {
          position: "top-right",
          autoClose: 2000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
        return;
      }
      // 申请连接，弹窗
      const account = ethereum.request({ method: "eth_requestAccounts" });
      setCurrentAccount(account[0]);
    } catch (e) {
      toast.error(`${e.message}`, {
        position: "top-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    }
  };

  const addNew = async () => {
    Router.push({pathname: '/addAddress', query: {}})
  };

  

  // 获取已购买的数组以便展示
  const getAllCoffee = async () => {
    try {
      const { ethereum } = window;
      if (ethereum) {
        const provider = new ethers.providers.Web3Provider(ethereum);
        const signer = provider.getSigner();
        const coffeeContract = new ethers.Contract(
          contractAddress,
          contractABI,
          signer
        );
        console.log("获取咖啡");
        const coffees = await coffeeContract.getAddresses();

        const finalCoffees = coffees.map((item) => {
          return {
            content: item.content,
            name: item.name,
            phone: item.phone,
           // timestamp: new Date(item.timestamp * 1000),
          };
        });
        console.log(finalCoffees);
        setAllCoffee(finalCoffees);

        console.log("------------#---------------", finalCoffees);
      } else {
        console.log("Ethereum object doesn't exist!");
      }
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    let coffeeContract;
    checkIfWalletIsConnected();

    getAllCoffee();

    // 监听时调用的函数
    const onNewAddress = (from, name, message, timestamp) => {
      setAllCoffee((pre) => [
        ...pre,
        {
          address: from,
          name: name,
          message: message,
          timestamp: new Date(timestamp * 1000),
        },
      ]);
    };

    if (window.ethereum) {
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();

      coffeeContract = new ethers.Contract(
        contractAddress,
        contractABI,
        signer
      );
      coffeeContract.on("NewAddress", onNewAddress);
    }

    return () => {
      // 关闭订阅的监听
      if (coffeeContract) {
        coffeeContract.off("NewAddress", onNewAddress);
      }
    };
  }, []);



  return (
    <div className="flex flex-col items-center justify-center min-h-screen py-1 bg-gray-100">
      <main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
       

      
         <Heading>Your Addresses</Heading>
  <Accordion>
        {allCoffee.map((coffee, index) => {
          return (
           
          
            <AccordionItem>
              <h2>
                <AccordionButton>
                  <Box as="span" flex='1' textAlign='left'>
                  {coffee.name}
                  </Box>
                  <AccordionIcon />
                </AccordionButton>
              </h2>
              <AccordionPanel pb={4}>
               <Text>cotactName: {coffee.name}</Text>
               <Text>address: {coffee.content}</Text>
               <Text>Phone: {coffee.phone}</Text>
              </AccordionPanel>
            </AccordionItem>

            // <div className="border-l-2 mt-10" key={index}>
            //   <div className="transform transition cursor-pointer hover:-translate-y-2 ml-10 relative flex items-center px-6 py-4 bg-green-600 text-white rounded mb-10 flex-col md:flex-row space-y-4 md:space-y-0">
            //     {/* <!-- Dot Following the Left Vertical Line --> */}
            //     <div className="w-5 h-5 bg-green-600 absolute -left-10 transform -translate-x-2/4 rounded-full z-10 mt-2 md:mt-0"></div>

            //     {/* <!-- Line that connecting the box with the vertical line --> */}
            //     <div className="w-10 h-1 bg-green-300 absolute -left-10 z-0"></div>

            //     {/* <!-- Content that showing in the box --> */}
            //     <div className="flex-auto">
            //       <h1 className="text-md">Supporter: {coffee.name}</h1>
            //       <h1 className="text-md">Message: {coffee.message}</h1>
            //       <h3>Address: {coffee.address}</h3>
            //       <h1 className="text-md font-bold">
            //         TimeStamp: {coffee.timestamp.toString()}
            //       </h1>
            //     </div>
            //   </div>
            // </div>
          );
        })}
 </Accordion>
 
 <Button type="button" w="100%" onClick={addNew}>
                  Add new
                </Button>
        <ToastContainer
          position="top-right"
          autoClose={5000}
          hideProgressBar={false}
          newestOnTop={false}
          closeOnClick
          rtl={false}
          pauseOnFocusLoss
          draggable
          pauseOnHover
        />
      </main>
    </div>
  );
}

export default App;
